package com.ruoyi.traplight.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.permission.Dao.SerDevicePermi;
import com.ruoyi.permission.domain.DevicePermiInsectInfo;
import com.ruoyi.permission.mapper.SerDevicePermiMapper;
import com.ruoyi.traplight.domain.TraplightDetectionLog;
import com.ruoyi.traplight.domain.SelectPhotoDao;
import com.ruoyi.traplight.mapper.ModelMapper;
import com.ruoyi.traplight.mapper.TrapLightDataMapper;
import com.ruoyi.traplight.service.ModelService;
import com.ruoyi.framework.web.service.TokenService;

import com.ruoyi.utils.ImgDrawCircleTool;
import com.ruoyi.utils.ParseString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Mr-Le
 */
@Service
@Slf4j
public class ModelServiceImpl implements ModelService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private TrapLightDataMapper dataMapper;

    @Autowired
    private SerDevicePermiMapper permiMapper;
    @Autowired
    private RedisCache redisCache;

    @Value("${ruoyi.profile}")
    private String profile;
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 新增图片检测信息
     * @param detectionLog  对象
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDetectionLog(TraplightDetectionLog detectionLog) {
        detectionLog.setCreateTime(DateUtils.getNowDate());
        return modelMapper.insertDetectionLog(detectionLog);
    }

    /**
     * 更新发送前端的对象，新增 检测结果 相关信息
     * @param webFrontEnd
     * @return
     */
//    @Override
//    public int updateWebFrontEnd(WebFrontEnd webFrontEnd) {
//        return modelMapper.updateWebFrontEnd(webFrontEnd);
//    }

    /**
     * @param id       图片编号
     * @param width    详情图的宽度
     * @param height   详情图的高度
     * @param type     害虫种类
     * @param position 画框位置 xywh
     * @param addOrCut 判断增加框还是减少框 ,1 代表增加 0 代表减少
     * @return
     * @throws IOException
     */
    @Override
    public SelectPhotoDao drawByManual(Integer unitId,Integer id, String width, String height, String type, String position, Integer addOrCut) throws IOException {
        SelectPhotoDao trapLightPhoto = dataMapper.selectPhotoById(id);
        //设备序列号
        String deviceSerial = trapLightPhoto.getDeviceName();
        SerDevicePermi serDevicePermi = permiMapper.selectByDeviceSerial(deviceSerial);
        Integer deviceId = serDevicePermi.getId();
//        String filename = trapLightPhoto.getPhotoName();
//        String[] splitFileName = StringUtils.split(filename, '_');
        String detectionImages = StringUtils.substringAfter(trapLightPhoto.getPhotoPath(), "profile");//例子：upload/2023/04/03/4be4cc70-60e0-4f10-a552-0c61658fa898__original.jpg
        File imgFile = new File(profile + detectionImages);
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imgFile));
        Integer originHeight = bufferedImage.getHeight();
        Integer originWidth = bufferedImage.getWidth();
        Integer drawWidth = null;
        if (width != null && width.length() != 0) {
            drawWidth = Integer.parseInt(width);
        }
        Integer drawHeight = null;
        if (height != null && height.length() != 0) {
            drawHeight = Integer.parseInt(height);
        }
        String[] positionsString = position.split(",");
        log.info("0:" + positionsString[0]);
        log.info("1:" + positionsString[1]);
        log.info("2:" + positionsString[2]);
        log.info("3:" + positionsString[3]);
        int size = positionsString.length;
        int[] positionsInt = new int[size];
        for (int i = 0; i < size; i++) {
            positionsInt[i] = Integer.parseInt(positionsString[i]);
        }
        String positionString = "";
        for (int i = 0; i < positionsInt.length / 4; i++) {
            positionsInt[4 * i + 2] = positionsInt[4 * i] + positionsInt[4 * i + 2];  //左上坐标 x，y,分别加上画框的宽高，得到右下角坐标
            positionsInt[4 * i + 3] = positionsInt[4 * i + 1] + positionsInt[4 * i + 3];
//            float scale = 1;//缩放比例
            float scaleWidth = 1;//缩放比例
            float scaleHeight = 1;//缩放比例
            if (originHeight != null && drawHeight != null && drawHeight != 0) {
//                scale = (float) originHeight / (float) drawHeight;
//            } else if (originWidth != null && drawWidth != null && drawWidth != 0) {
//                scale = (float) originWidth / (float) drawWidth;
                scaleHeight = (float) originHeight / (float) drawHeight;
            }
            if (originWidth != null && drawWidth != null && drawWidth != 0) {
                scaleWidth = (float) originWidth / (float) drawWidth;
            }
            if(drawWidth == null || drawWidth == 0) {
                scaleWidth = scaleHeight;
            }
            if(drawHeight == null || drawHeight == 0){
                scaleHeight=scaleWidth;
            }



//            drawHeightlog.info("scale =" + scale);
            log.info("scaleHeight =" + scaleHeight);
            log.info("scaleWidth =" + scaleWidth);
            positionsInt[4 * i] = (int) (positionsInt[4 * i] * scaleWidth);
            positionsInt[4 * i + 1] = (int) (positionsInt[4 * i + 1] * scaleHeight);
            positionsInt[4 * i + 2] = (int) (positionsInt[4 * i + 2] * scaleWidth);
            positionsInt[4 * i + 3] = (int) (positionsInt[4 * i + 3] * scaleHeight);
//            positionsInt[4 * i] = (int) (positionsInt[4 * i] * scale);
//            positionsInt[4 * i + 1] = (int) (positionsInt[4 * i + 1] * scale);
//            positionsInt[4 * i + 2] = (int) (positionsInt[4 * i + 2] * scale);
//            positionsInt[4 * i + 3] = (int) (positionsInt[4 * i + 3] * scale);
            positionString = positionString + ",[" + positionsInt[4 * i] + "," + positionsInt[4 * i + 1] + "," + positionsInt[4 * i + 2] + "," + positionsInt[4 * i + 3] + "]";
        }
        log.info(positionString);
        //若为添加画框
        if (addOrCut == 1) {
            //如果添加画框的是管理员，则不修改对于user的结果图.

                String tagForDraw = "";
                if (trapLightPhoto.getTagForDraw() != null && trapLightPhoto.getTagForDraw().length() != 0) {
                    tagForDraw = trapLightPhoto.getTagForDraw();
                    tagForDraw = tagForDraw.split("]")[0];
                } else {
                    tagForDraw = "[";
                }
                for (int i = 0; i < positionsString.length / 4; i++) {
                    tagForDraw = tagForDraw + "," + "\"" + type + "\"";
                }
                tagForDraw = tagForDraw + "]";
                tagForDraw = tagForDraw.replace("[,", "[");
                trapLightPhoto.setTagForDraw(tagForDraw);
                String corner = "";
                log.info("原始corner:" + trapLightPhoto.getCorner());
                if (trapLightPhoto.getCorner() != null && !trapLightPhoto.getCorner().isEmpty()) {
                    log.info(trapLightPhoto.getCorner().substring(1, trapLightPhoto.getCorner().length() - 1));
                    corner = trapLightPhoto.getCorner().substring(1, trapLightPhoto.getCorner().length() - 1) + positionString;
                    corner = "[" + corner + "]";
                } else {
                    corner = corner + positionString.replaceFirst(",", "");
                    corner = "[" + corner + "]";
                }
                trapLightPhoto.setCorner(corner);
                log.info("修改后的corner:" + corner);
//            trapLightPhoto.setTagManual(ParseString.getTagNum(tagForDraw));
                ArrayList<int[]> cornerList = new ArrayList<>();
                String[] corners = corner.replaceAll("\\[", "").replaceAll("]", "").split(",");
                log.info(corner.replaceAll("\\[", "").replaceAll("]", ""));

                size = corners.length;
                int[] cornerInt = new int[size];
                for (int i = 0; i < size; i++) {
                    cornerInt[i] = Integer.parseInt(corners[i]);
                }
                for (int i = 0; i < cornerInt.length / 4; i++) {
                    int[] cornerArray = Arrays.copyOfRange(cornerInt, i * 4, i * 4 + 4);
                    cornerList.add(cornerArray);
                }
                for (int[] arr : cornerList) {
                    log.info(Arrays.toString(arr));
                }

                String tagNum = ParseString.getTagNum(tagForDraw);
                log.info("检测结果：" + tagNum);
                log.info("tagforDraw :" + tagForDraw);
                JSONObject jsonObject = JSON.parseObject(tagNum);
                int num_y1 = 0, num_y2 = 0, num_y3 = 0, num_y4 = 0, num_y5 = 0, num_y6 = 0, num_y7 = 0, num_y8 = 0,
                        num_y9 = 0, num_e1 = 0, num_e2 = 0, num_e3 = 0, num_e4 = 0, num_e5 = 0, num_e6 = 0,
                        num_e7 = 0, num_e8 = 0, num_e9 = 0, num_e10 = 0, num_e11 = 0, num_e12 = 0, num_q1 = 0, num_q2 = 0,
                        num_q3 = 0, num_q4 = 0, num_q5 = 0, num_q6 = 0, num_q7 = 0, num_q8 = 0, num_q9 = 0, num_q10 = 0,
                        num_q11 = 0, num_q12 = 0, num_q13 = 0, num_q14 = 0, num_q15 = 0, num_q16 = 0, num_q17 = 0, num_q18 = 0,
                        num_x1 = 0, num_x2 = 0, num_x3 = 0, num_e120 = 0, num_e90 = 0, num_e40 = 0, num_a41 = 0,num_a10 = 0;
                if (jsonObject.get("y1") != null) {num_y1 = (int) jsonObject.get("y1");}
                if (jsonObject.get("y2") != null) {num_y2 = (int) jsonObject.get("y2");}
                if (jsonObject.get("y3") != null) {num_y3 = (int) jsonObject.get("y3");}
                if (jsonObject.get("y4") != null) {num_y4 = (int) jsonObject.get("y4");}
                if (jsonObject.get("y5") != null) {num_y5 = (int) jsonObject.get("y5");}
                if (jsonObject.get("y6") != null) {num_y6 = (int) jsonObject.get("y6");}
                if (jsonObject.get("y7") != null) {num_y7 = (int) jsonObject.get("y7");}
                if (jsonObject.get("y8") != null) {num_y8 = (int) jsonObject.get("y8");}
                if (jsonObject.get("y9") != null) {num_y9 = (int) jsonObject.get("y9");}
                if (jsonObject.get("e1") != null) {num_e1 = (int) jsonObject.get("e1");}
                if (jsonObject.get("e2") != null) {num_e2 = (int) jsonObject.get("e2");}
                if (jsonObject.get("e3") != null) {num_e3 = (int) jsonObject.get("e3");}
                if (jsonObject.get("e4") != null) {num_e4 = (int) jsonObject.get("e4");}
                if (jsonObject.get("e5") != null) {num_e5 = (int) jsonObject.get("e5");}
                if (jsonObject.get("e6") != null) {num_e6 = (int) jsonObject.get("e6");}
                if (jsonObject.get("e7") != null) {num_e7 = (int) jsonObject.get("e7");}
                if (jsonObject.get("e8") != null) {num_e8 = (int) jsonObject.get("e8");}
                if (jsonObject.get("e9") != null) {num_e9 = (int) jsonObject.get("e9");}
                if (jsonObject.get("e10") != null) {num_e10 = (int) jsonObject.get("e10");}
                if (jsonObject.get("e11") != null) {num_e11 = (int) jsonObject.get("e11");}
                if (jsonObject.get("e12") != null) {num_e12 = (int) jsonObject.get("e12");}
                if (jsonObject.get("q1") != null) {num_q1 = (int) jsonObject.get("q1");}
                if (jsonObject.get("q2") != null) {num_q2 = (int) jsonObject.get("q2");}
                if (jsonObject.get("q3") != null) {num_q3 = (int) jsonObject.get("q3");}
                if (jsonObject.get("q4") != null) {num_q4 = (int) jsonObject.get("q4");}
                if (jsonObject.get("q5") != null) {num_q5 = (int) jsonObject.get("q5");}
                if (jsonObject.get("q6") != null) {num_q6 = (int) jsonObject.get("q6");}
                if (jsonObject.get("q7") != null) {num_q7 = (int) jsonObject.get("q7");}
                if (jsonObject.get("q8") != null) {num_q8 = (int) jsonObject.get("q8");}
                if (jsonObject.get("q9") != null) {num_q9 = (int) jsonObject.get("q9");}
                if (jsonObject.get("q10") != null) {num_q10 = (int) jsonObject.get("q10");}
                if (jsonObject.get("q11") != null) {num_q11 = (int) jsonObject.get("q11");}
                if (jsonObject.get("q12") != null) {num_q12 = (int) jsonObject.get("q12");}
                if (jsonObject.get("q13") != null) {num_q13 = (int) jsonObject.get("q13");}
                if (jsonObject.get("q14") != null) {num_q14 = (int) jsonObject.get("q14");}
                if (jsonObject.get("q15") != null) {num_q15 = (int) jsonObject.get("q15");}
                if (jsonObject.get("q16") != null) {num_q16 = (int) jsonObject.get("q16");}
                if (jsonObject.get("q17") != null) {num_q17 = (int) jsonObject.get("q17");}
                if (jsonObject.get("q18") != null) {num_q18 = (int) jsonObject.get("q18");}
                if (jsonObject.get("x1") != null) {num_x1 = (int) jsonObject.get("x1");}
                if (jsonObject.get("x2") != null) {num_x2 = (int) jsonObject.get("x2");}
                if (jsonObject.get("x3") != null) {num_x3 = (int) jsonObject.get("x3");}
                if (jsonObject.get("e120") != null) {num_e120 = (int) jsonObject.get("e120");}
                if (jsonObject.get("e90") != null) {num_e90 = (int) jsonObject.get("e90");}
                if (jsonObject.get("e40") != null) {num_e40 = (int) jsonObject.get("e40");}
                if (jsonObject.get("a41") != null) {num_a41 = (int) jsonObject.get("a41");}
                if (jsonObject.get("a10") != null) {num_a10 = (int) jsonObject.get("a10");}

                String tagManual = numberToJsonTag(num_y1, num_y2, num_y3, num_y4, num_y5, num_y6, num_y7, num_y8,
                        num_y9, num_e1, num_e2, num_e3, num_e4, num_e5, num_e6, num_e7, num_e8,
                        num_e9, num_e10, num_e11, num_e12, num_q1, num_q2, num_q3, num_q4, num_q5,
                        num_q6, num_q7, num_q8, num_q9, num_q10, num_q11, num_q12, num_q13, num_q14,
                        num_q15, num_q16, num_q17, num_q18, num_x1, num_x2, num_x3, num_e120, num_e90,
                        num_e40, num_a41, num_a10);

                trapLightPhoto.setTagManual(tagManual);
                ImgDrawCircleTool tool = new ImgDrawCircleTool();
                List<String> tagList = JSON.parseArray(tagForDraw, String.class);
//                如果不为管理员则对应修改用户的结果图
            if(unitId != 0) {
                //获取虫情权限
                List<DevicePermiInsectInfo> insectPermiLst = permiMapper.selectInsectListByDeviceId(deviceId);
                //用于存储权限虫子的编号
                List<String> retLst = new ArrayList<>();
                for (DevicePermiInsectInfo insectPermi : insectPermiLst) {
                    String ret = insectPermi.getRet();
                    if (!retLst.contains(ret)) {
                        retLst.add(ret);
                    }
                }
                //用户独属的框信息
                List<int[]> cornerListForUser = new ArrayList<>(cornerList);
                //用户独属的虫子信息
                List<String> tagListForUser = new ArrayList<>(tagList);
                //在遍历tagList的过程中，记录需要删除的索引位置
                List<Integer> indexesToRemove = new ArrayList<>();
                for (int i = 0; i < tagListForUser.size(); i++) {
                    String tagValue = tagListForUser.get(i);
                    if (!retLst.contains(tagValue)) {
                        indexesToRemove.add(i);
                    }
                }
                //删除不需要的虫子信息
                for (int i = indexesToRemove.size() - 1; i >= 0; i--) {
                    int indexToRemove = indexesToRemove.get(i);
                    tagListForUser.remove(indexToRemove);
                    cornerListForUser.remove(indexToRemove);
                }
                log.info("tagForUser: " + tagListForUser.toString() + "\ncornerForUser:" + JSON.toJSONString(cornerListForUser));
                if (!tagListForUser.isEmpty() && !cornerListForUser.isEmpty()) {
                    trapLightPhoto.setTagForUser(ParseString.getTagNum(JSON.toJSONString(tagListForUser))).setCornerForUser(JSON.toJSONString(cornerListForUser));
                }
                //绘制用户专属的结果图片
                if (!tagListForUser.isEmpty() && !cornerListForUser.isEmpty()) {
                    String resultPathForUser = tool.doDrawRectangleForUnit(unitId, cornerListForUser, tagListForUser, profile + detectionImages).replace(profile, Constants.RESOURCE_PREFIX);
                    log.info("用户的结果图的url：" + resultPathForUser);
                }
            }
                String resultPath = tool.doDrawRectangleT(cornerList, tagList, profile + detectionImages).replace(profile, Constants.RESOURCE_PREFIX);
                trapLightPhoto.setResultPath(resultPath);

        }else if(addOrCut == 0){
            //删去画框
            String tagForCut; //   tagForCut：删除画框后的tag
            tagForCut = trapLightPhoto.getTagForDraw();
            log.info(tagForCut);
            tagForCut = tagForCut.replace("[","").replace("]","");
            String[] tagForCutString= tagForCut.split(",");
            log.info("原画框手动修改的tag" + Arrays.toString(tagForCutString));
            String oriCorner = trapLightPhoto.getCorner();//原始框信息
            String[] oriCorners = oriCorner.replaceAll("\\[","").replaceAll("]","").split(",");
            log.info(oriCorner.replaceAll("\\[","").replaceAll("]",""));
            Integer length = oriCorners.length;
            int[] oriCornerInt = new int[length];
            for(int i = 0; i < length; i++){
                oriCornerInt[i] = Integer.parseInt(oriCorners[i]);
            }
            List<String> tagForCutList = Arrays.asList(tagForCutString);
            List<String> arrList = new ArrayList<>(tagForCutList);//为了避免出现UnsupportedOperationException错误
            List<String> tagForCutListNew = new ArrayList<>();
            log.info("删减前的tagList" + arrList);
            List<Integer> record = new ArrayList<>();//记录下标
            List<Integer> recordList = new ArrayList<>(record);
            //在cornerInt数组里寻找被positionInt包含的数
            for(int i = 0; i < length / 4; i++){ // i:0 1 2
                int[] cornerArray = Arrays.copyOfRange(oriCornerInt, i * 4, i * 4 + 4);
                for(int j = 0 ;j < positionsInt.length / 4; j++){ // j:0 1
                    int[] positionArray = Arrays.copyOfRange(positionsInt,j * 4,j * 4 + 4);
                    if(IsContain(positionArray,cornerArray) && arrList.get(i).equals("\""+type+"\"")){
                        recordList.add(i);
                        log.info("记录的下标为:" + recordList);
                    }
                }
            }

            int sizeNew = recordList.size();
            for(int i = 0;i < arrList.size();i++){
                if(recordList.contains(i)){
                    continue;
                }
                tagForCutListNew.add(arrList.get(i));
            }
            log.info("tagForCutListNew: " + tagForCutListNew);
            int [] positionIntNew = new int[sizeNew * 4];//对应属于图上的框
            log.info("oriCornerInt = " + Arrays.toString(oriCornerInt));
            log.info("recordList = " + recordList);
            positionIntNew = getTheElement(oriCornerInt,recordList);

            log.info("positionIntNew:" + Arrays.toString(positionIntNew));

            String positionStringNew="";
            for(int i =0; i < sizeNew; i++){
                positionStringNew = positionStringNew + ",[" +positionIntNew[4 * i] + "," + positionIntNew[4 * i + 1] + "," + positionIntNew[4 * i + 2] + "," + positionIntNew[4 * i + 3] + "]";
            }
            positionStringNew = positionStringNew.replaceFirst(",", "");
            log.info("positionStringNew:" + positionStringNew);
            //log.info("删减后的tagList" + tagForCutListNew);
            String tagForCutByJoin = StringUtils.join(tagForCutListNew,",");
            if(tagForCutByJoin !="") {
                tagForCut = "[" + tagForCutByJoin + "]";
            }else {
                tagForCut = tagForCutByJoin;
            }
            log.info("删减后的tag:" + tagForCut);
            trapLightPhoto.setTagForDraw(tagForCut);
//            1962,1091,2045,1179,2080,955,2270,1018,1074,729,1260,852,1403,733,1597,856,
            String corner = trapLightPhoto.getCorner().replace( positionStringNew,"");
            corner = StringUtils.removeEnd(corner,"]");
            corner = corner.replaceFirst("\\[","");
            corner = corner.replaceAll(",{2,}",",");
            if(corner.endsWith(",")){
                corner = StringUtils.removeEnd(corner,",");
            }
            if(corner.startsWith(",")){
                corner = corner.replaceFirst(",","");
            }
            if(corner != "" && !corner.isEmpty()) {
                corner = "[" + corner + "]";
            }
            log.info("corner: " + corner);
            trapLightPhoto.setCorner(corner);
            corner = corner.replaceAll("\\[","").replaceAll("]","");
            ArrayList<int[]> cornerList = new ArrayList<>();
            if(!corner.isEmpty()){

                String[] corners = corner.split(",");
                log.info(Arrays.toString(corners));
                size = corners.length;
                log.info("size:" + size);
                int[] cornerInt = new int[size];
                for (int i = 0; i < size; i++) {
                    cornerInt[i] = Integer.parseInt(corners[i]);
                }
                for (int i = 0; i < cornerInt.length / 4; i++) {

                    int[] cornerArray = Arrays.copyOfRange(cornerInt, i * 4, i * 4 + 4);
                    cornerList.add(cornerArray);
                }
            }
            String tagNum = ParseString.getTagNum(tagForCut);
            log.info("检测结果：" + tagNum);
            JSONObject jsonObject = JSON.parseObject(tagNum);
            int num_y1 = 0, num_y2 = 0, num_y3 = 0, num_y4 = 0, num_y5 = 0, num_y6 = 0, num_y7 = 0, num_y8 = 0,
                    num_y9 = 0, num_e1 = 0, num_e2 = 0, num_e3 = 0, num_e4 = 0, num_e5 = 0, num_e6 = 0,
                    num_e7 = 0, num_e8 = 0, num_e9 = 0, num_e10 = 0, num_e11 = 0, num_e12 = 0, num_q1 = 0, num_q2 = 0,
                    num_q3 = 0, num_q4 = 0, num_q5 = 0, num_q6 = 0, num_q7 = 0, num_q8 = 0, num_q9 = 0, num_q10 = 0,
                    num_q11 = 0, num_q12 = 0, num_q13 = 0, num_q14 = 0, num_q15 = 0, num_q16 = 0, num_q17 = 0, num_q18 = 0,
                    num_x1 = 0, num_x2 = 0, num_x3 = 0, num_e120 = 0, num_e90 = 0, num_e40 = 0, num_a41 = 0, num_a10 = 0;
            if (jsonObject !=null){
                if (jsonObject.get("y1") != null) {num_y1 = (int) jsonObject.get("y1");}
                if (jsonObject.get("y2") != null) {num_y2 = (int) jsonObject.get("y2");}
                if (jsonObject.get("y3") != null) {num_y3 = (int) jsonObject.get("y3");}
                if (jsonObject.get("y4") != null) {num_y4 = (int) jsonObject.get("y4");}
                if (jsonObject.get("y5") != null) {num_y5 = (int) jsonObject.get("y5");}
                if (jsonObject.get("y6") != null) {num_y6 = (int) jsonObject.get("y6");}
                if (jsonObject.get("y7") != null) {num_y7 = (int) jsonObject.get("y7");}
                if (jsonObject.get("y8") != null) {num_y8 = (int) jsonObject.get("y8");}
                if (jsonObject.get("y9") != null) {num_y9 = (int) jsonObject.get("y9");}
                if (jsonObject.get("e1") != null) {num_e1 = (int) jsonObject.get("e1");}
                if (jsonObject.get("e2") != null) {num_e2 = (int) jsonObject.get("e2");}
                if (jsonObject.get("e3") != null) {num_e3 = (int) jsonObject.get("e3");}
                if (jsonObject.get("e4") != null) {num_e4 = (int) jsonObject.get("e4");}
                if (jsonObject.get("e5") != null) {num_e5 = (int) jsonObject.get("e5");}
                if (jsonObject.get("e6") != null) {num_e6 = (int) jsonObject.get("e6");}
                if (jsonObject.get("e7") != null) {num_e7 = (int) jsonObject.get("e7");}
                if (jsonObject.get("e8") != null) {num_e8 = (int) jsonObject.get("e8");}
                if (jsonObject.get("e9") != null) {num_e9 = (int) jsonObject.get("e9");}
                if (jsonObject.get("e10") != null) {num_e10 = (int) jsonObject.get("e10");}
                if (jsonObject.get("e11") != null) {num_e11 = (int) jsonObject.get("e11");}
                if (jsonObject.get("e12") != null) {num_e12 = (int) jsonObject.get("e12");}
                if (jsonObject.get("q1") != null) {num_q1 = (int) jsonObject.get("q1");}
                if (jsonObject.get("q2") != null) {num_q2 = (int) jsonObject.get("q2");}
                if (jsonObject.get("q3") != null) {num_q3 = (int) jsonObject.get("q3");}
                if (jsonObject.get("q4") != null) {num_q4 = (int) jsonObject.get("q4");}
                if (jsonObject.get("q5") != null) {num_q5 = (int) jsonObject.get("q5");}
                if (jsonObject.get("q6") != null) {num_q6 = (int) jsonObject.get("q6");}
                if (jsonObject.get("q7") != null) {num_q7 = (int) jsonObject.get("q7");}
                if (jsonObject.get("q8") != null) {num_q8 = (int) jsonObject.get("q8");}
                if (jsonObject.get("q9") != null) {num_q9 = (int) jsonObject.get("q9");}
                if (jsonObject.get("q10") != null) {num_q10 = (int) jsonObject.get("q10");}
                if (jsonObject.get("q11") != null) {num_q11 = (int) jsonObject.get("q11");}
                if (jsonObject.get("q12") != null) {num_q12 = (int) jsonObject.get("q12");}
                if (jsonObject.get("q13") != null) {num_q13 = (int) jsonObject.get("q13");}
                if (jsonObject.get("q14") != null) {num_q14 = (int) jsonObject.get("q14");}
                if (jsonObject.get("q15") != null) {num_q15 = (int) jsonObject.get("q15");}
                if (jsonObject.get("q16") != null) {num_q16 = (int) jsonObject.get("q16");}
                if (jsonObject.get("q17") != null) {num_q17 = (int) jsonObject.get("q17");}
                if (jsonObject.get("q18") != null) {num_q18 = (int) jsonObject.get("q18");}
                if (jsonObject.get("x1") != null) {num_x1 = (int) jsonObject.get("x1");}
                if (jsonObject.get("x2") != null) {num_x2 = (int) jsonObject.get("x2");}
                if (jsonObject.get("x3") != null) {num_x3 = (int) jsonObject.get("x3");}
                if (jsonObject.get("e120") != null) {num_e120 = (int) jsonObject.get("e120");}
                if (jsonObject.get("e90") != null) {num_e90 = (int) jsonObject.get("e90");}
                if (jsonObject.get("e40") != null) {num_e40 = (int) jsonObject.get("e40");}
                if (jsonObject.get("a41") != null) {num_a41 = (int) jsonObject.get("a41");}
                if (jsonObject.get("a10") != null) {num_a10 = (int) jsonObject.get("a10");}
            }
            String tagManual = numberToJsonTag(num_y1,num_y2,num_y3,num_y4,num_y5,num_y6,num_y7,num_y8,num_y9,num_e1,num_e2,num_e3,num_e4,num_e5,num_e6,
                    num_e7,num_e8,num_e9,num_e10,num_e11,num_e12,num_q1,num_q2,num_q3,num_q4,num_q5,num_q6,num_q7,num_q8,num_q9,num_q10,num_q11,num_q12,num_q13
            ,num_q14,num_q15,num_q16,num_q17,num_q18,num_x1,num_x2,num_x3,num_e120,num_e90,num_e40,num_a41,num_a10);
            trapLightPhoto.setTagManual(tagManual);
            ImgDrawCircleTool tool = new ImgDrawCircleTool();

            List<String> tagList = JSON.parseArray(tagForCut, String.class);
            // 如果不为管理员则对应修改用户的结果图
            if(unitId != 0) {

                //获取虫情权限
                List<DevicePermiInsectInfo> insectPermiLst = permiMapper.selectInsectListByDeviceId(deviceId);
                //用于存储权限虫子的编号
                List<String> retLst = new ArrayList<>();
                for (DevicePermiInsectInfo insectPermi : insectPermiLst) {
                    String ret = insectPermi.getRet();
                    if (!retLst.contains(ret)) {
                        retLst.add(ret);
                    }
                }
                //用户独属的框信息
                List<int[]> cornerListForUser = new ArrayList<>(cornerList);
                //用户独属的虫子信息
                List<String> tagListForUser = new ArrayList<>(tagList);
                //在遍历tagList的过程中，记录需要删除的索引位置
                List<Integer> indexesToRemove = new ArrayList<>();
                for (int i = 0; i < tagListForUser.size(); i++) {
                    String tagValue = tagListForUser.get(i);
                    if (!retLst.contains(tagValue)) {
                        indexesToRemove.add(i);
                    }
                }
                //删除不需要的虫子信息
                for (int i = indexesToRemove.size() - 1; i >= 0; i--) {
                    int indexToRemove = indexesToRemove.get(i);
                    tagListForUser.remove(indexToRemove);
                    cornerListForUser.remove(indexToRemove);
                }
                log.info("tagForUser: " + tagListForUser.toString() + "\ncornerForUser:" + JSON.toJSONString(cornerListForUser));
                if (tagListForUser.size() != 0 && cornerListForUser.size() != 0) {
                    trapLightPhoto.setTagForUser(ParseString.getTagNum(JSON.toJSONString(tagListForUser))).setCornerForUser(JSON.toJSONString(cornerListForUser));
                }
                //绘制用户专属的结果图片
                if (tagListForUser.size() != 0 && cornerListForUser.size() != 0) {
                    String resultPathForUser = tool.doDrawRectangleForUnit(unitId, cornerListForUser, tagListForUser, profile + detectionImages).replace(profile, Constants.RESOURCE_PREFIX);
                    log.info("用户的结果图的url：" + resultPathForUser);
                }
            }
            log.info("tagList:" + tagList);
            log.info("cornerList: " + cornerList);
            String resultPath = null;
            if(tool.doDrawRectangleT(cornerList, tagList, profile + detectionImages) !=null) {
                resultPath = tool.doDrawRectangleT(cornerList, tagList, profile + detectionImages).replace(profile, Constants.RESOURCE_PREFIX);
            }
            log.info("resultPath:" + resultPath);
            trapLightPhoto.setResultPath(resultPath);

        }
        dataMapper.updatePhotoInfoById(trapLightPhoto);
        return dataMapper.selectPhotoById(id);
    }
    /**
     * 从oriCornerInt(框信息)中取出指定元素  1个下标取连续4个元素
     * @param oriCornerInt
     * @param index
     * @return
     */
    private int[] getTheElement(int[] oriCornerInt, List<Integer> index) {
        int[] cornerInt = new int[index.size() * 4];
        for(int i = 0;i < index.size();i++) {
            cornerInt[4 * i] = oriCornerInt[index.get(i) * 4];
            cornerInt[4 * i + 1] = oriCornerInt[index.get(i) * 4 + 1];
            cornerInt[4 * i + 2] = oriCornerInt[index.get(i) * 4 + 2];
            cornerInt[4 * i + 3] = oriCornerInt[index.get(i) * 4 + 3];
        }
        return cornerInt;
    }

    /**
     * 删除画框时调用
     * 比较前端传来的画框信息是否在原画框信息中
     * @param positionArray  前端传来的画框信息转化的数组
     * @param cornerArray  原画框信息转化的数组
     * @return
     */
    private boolean IsContain(int[]positionArray,int[]cornerArray) {
        if (positionArray.length != 0 && cornerArray.length != 0) {
            int length = positionArray.length;  //4
            if (positionArray[0] <= cornerArray[0] && positionArray[1] <= cornerArray[1] && positionArray[2] >= cornerArray[2] && positionArray[3] >= cornerArray[3]) {
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }
    }
    /**
     * 将虫子数量转成tag标签
     *
     * @param
     * @return 等级
     */
    public static String numberToJsonTag(Integer num_y1, Integer num_y2, Integer num_y3, Integer num_y4, Integer num_y5,
                                         Integer num_y6, Integer num_y7, Integer num_y8, Integer num_y9, Integer num_e1,
                                         Integer num_e2, Integer num_e3, Integer num_e4, Integer num_e5, Integer num_e6,
                                         Integer num_e7, Integer num_e8, Integer num_e9, Integer num_e10, Integer num_e11,
                                         Integer num_e12, Integer num_q1, Integer num_q2, Integer num_q3, Integer num_q4,
                                         Integer num_q5, Integer num_q6, Integer num_q7, Integer num_q8, Integer num_q9,
                                         Integer num_q10, Integer num_q11, Integer num_q12, Integer num_q13, Integer num_q14,
                                         Integer num_q15, Integer num_q16, Integer num_q17, Integer num_q18, Integer num_x1,
                                         Integer num_x2, Integer num_x3, Integer num_e120, Integer num_e90, Integer num_e40,
                                         Integer num_a41, Integer num_a10) {

        String tagManual = "{";
//        String otherTag = "";

//        String hfs = ""; String bbfs = ""; String ehm = ""; String dzjym = ""; String ymm = ""; String cdm = ""; String dfnc = ""; String lsnc = "";
//        String cdtye = ""; String dm = ""; String xwye = ""; String mlc = ""; String xce = ""; String tzm = ""; String lxsxc = ""; String xdlh ="";
//        String bzdlh =""; String tlljg =""; String dhsjg =""; String tcye = ""; String edwye = ""; String lmc = ""; String shm =""; String xlyc ="";
//        String kj =""; String ahsjg =""; String sjye = ""; String jwdlh = ""; String hzdlh =""; String dgyc =""; String dhc ="";String hzlc ="";
//        String cl ="";String gjm ="";String tcbdym ="";String qcyxycj = "";String xs ="";String pj ="";String lgl ="";String xwye2 ="";String pgce ="";
//        String smc ="";String gllwce ="";String yhzde ="";String yxde ="";String gsce ="";String jhlcye ="";
        String[] variables = {
                "hfs", "bbfs", "ehm", "dzjym", "ymm", "cdm", "dfnc", "lsnc",
                "cdtye", "dm", "xwye", "mlc", "xce", "tzm", "lxsxc", "xdlh",
                "bzdlh", "tlljg", "dhsjg", "tcye", "edwye", "lmc", "shm", "xlyc",
                "kj", "ahsjg", "sjye", "jwdlh", "hzdlh", "dgyc", "dhc", "hzlc",
                "cl", "gjm", "tcbdym", "qcyxycj", "xs", "pj", "lgl", "xwye2", "pgce",
                "smc", "gllwce", "yhzde", "yxde", "gsce", "jhlcye"
        };

        int flag=0;
        if (num_y1 >= 0) {variables[0] = "\"y1\":" + Integer.toString(num_y1);}
        if (num_y2 >= 0) {variables[1] = "\"y2\":" + Integer.toString(num_y2);}
        if (num_y3 >= 0) {variables[2] = "\"y3\":" + Integer.toString(num_y3);}
        if (num_y4 >= 0) {variables[3] = "\"y4\":" + Integer.toString(num_y4);}
        if (num_y5 >= 0) {variables[4] = "\"y5\":" + Integer.toString(num_y5);}
        if (num_y6 >= 0) {variables[5] = "\"y6\":" + Integer.toString(num_y6);}
        if (num_y7 >= 0) {variables[6] = "\"y7\":" + Integer.toString(num_y7);}
        if (num_y8 >= 0) {variables[7] = "\"y8\":" + Integer.toString(num_y8);}
        if (num_y9 >= 0) {variables[8] = "\"y9\":" + Integer.toString(num_y9);}
        if (num_e1 >= 0) {variables[9] = "\"e1\":" + Integer.toString(num_e1);}
        if (num_e2 >= 0) {variables[10] = "\"e2\":" + Integer.toString(num_e2);}
        if (num_e3 >= 0) {variables[11] = "\"e3\":" + Integer.toString(num_e3);}
        if (num_e4 >= 0) {variables[12] = "\"e4\":" + Integer.toString(num_e4);}
        if (num_e5 >= 0) {variables[13] = "\"e5\":" + Integer.toString(num_e5);}
        if (num_e6 >= 0) {variables[14] = "\"e6\":" + Integer.toString(num_e6);}
        if (num_e7 >= 0) {variables[15] = "\"e7\":" + Integer.toString(num_e7);}
        if (num_e8 >= 0) {variables[16] = "\"e8\":" + Integer.toString(num_e8);}
        if (num_e9 >= 0) {variables[17] = "\"e9\":" + Integer.toString(num_e9);}
        if (num_e10 >= 0) {variables[18] = "\"e10\":" + Integer.toString(num_e10);}
        if (num_e11 >= 0) {variables[19] = "\"e11\":" + Integer.toString(num_e11);}
        if (num_e12 >= 0) {variables[20] = "\"e12\":" + Integer.toString(num_e12);}
        if (num_q1 >= 0) {variables[21] = "\"q1\":" + Integer.toString(num_q1);}
        if (num_q2 >= 0) {variables[22] = "\"q2\":" + Integer.toString(num_q2);}
        if (num_q3 >= 0) { variables[23] = "\"q3\":" + Integer.toString(num_q3); }
        if (num_q4 >= 0) { variables[24] = "\"q4\":" + Integer.toString(num_q4); }
        if (num_q5 >= 0) { variables[25] = "\"q5\":" + Integer.toString(num_q5); }
        if (num_q6 >= 0) { variables[26] = "\"q6\":" + Integer.toString(num_q6); }
        if (num_q7 >= 0) { variables[27] = "\"q7\":" + Integer.toString(num_q7); }
        if (num_q8 >= 0) { variables[28] = "\"q8\":" + Integer.toString(num_q8); }
        if (num_q9 >= 0) { variables[29] = "\"q9\":" + Integer.toString(num_q9); }
        if (num_q10 >= 0) { variables[30] = "\"q10\":" + Integer.toString(num_q10); }
        if (num_q11 >= 0) { variables[31] = "\"q11\":" + Integer.toString(num_q11); }
        if (num_q12 >= 0) { variables[32] = "\"q12\":" + Integer.toString(num_q12); }
        if (num_q13 >= 0) { variables[33] = "\"q13\":" + Integer.toString(num_q13); }
        if (num_q14 >= 0) { variables[34] = "\"q14\":" + Integer.toString(num_q14); }
        if (num_q15 >= 0) { variables[35] = "\"q15\":" + Integer.toString(num_q15); }
        if (num_q16 >= 0) { variables[36] = "\"q16\":" + Integer.toString(num_q16); }
        if (num_q17 >= 0) { variables[37] = "\"q17\":" + Integer.toString(num_q17); }
        if (num_q18 >= 0) { variables[38] = "\"q18\":" + Integer.toString(num_q18); }
        if (num_x1 >= 0) { variables[39] = "\"x1\":" + Integer.toString(num_x1); }
        if (num_x2 >= 0) { variables[40] = "\"x2\":" + Integer.toString(num_x2); }
        if (num_x3 >= 0) { variables[41] = "\"x3\":" + Integer.toString(num_x3); }
        if (num_e120 >= 0) { variables[42] = "\"e120\":" + Integer.toString(num_e120); }
        if (num_e90 >= 0) { variables[43] = "\"e90\":" + Integer.toString(num_e90); }
        if (num_e40 >= 0) { variables[44] = "\"e40\":" + Integer.toString(num_e40); }
        if (num_a41 >= 0) { variables[45] = "\"a41\":" + Integer.toString(num_a41); }
        if (num_a10 >= 0) { variables[46] = "\"a10\":" + Integer.toString(num_a10); }

//        if(!hfs.equals("")){tagManual += hfs;flag = 1;}
//        if((flag == 1) && (!bbfs.equals(""))) {tagManual += ",";flag = 0;}
//        if(!bbfs.equals("")){tagManual += bbfs;flag = 1;}
//        if ((flag == 1) && (!ehm.equals(""))) { tagManual += ","; flag = 0; }
//        if (!ehm.equals("")) { tagManual += ehm; flag = 1; }
//        if ((flag == 1) && (!dzjym.equals(""))) { tagManual += ","; flag = 0; }
//        if (!dzjym.equals("")) { tagManual += dzjym; flag = 1; }
//        if ((flag == 1) && (!dzjym.equals(""))) { tagManual += ","; flag = 0; }
        for (String variable : variables) {
            if (!variable.equals("")) {
                if (flag == 1) {
                    tagManual += ",";
                    flag = 0;
                }
                tagManual += variable;
                flag = 1;
            }
        }
        tagManual += "}";
        return tagManual;
    }


}
